1
Introduction à PyTorch : Pourquoi les tenseurs sont importants
EvoClass-AI002Lecture 1
00:00

Introduction à PyTorch : Pourquoi les tenseurs sont importants

PyTorch est un cadre open source très flexible et dynamique, apprécié pour la recherche en apprentissage profond et le prototypage rapide. Au cœur de ce système, le tenseur constitue la structure de données incontournable. Il s'agit d'un tableau multidimensionnel conçu pour traiter efficacement les opérations numériques nécessaires aux modèles d'apprentissage profond, en prenant en charge automatiquement l'accélération GPU automatically.

1. Comprendre la structure des tenseurs

Tout entrée, sortie et paramètre de modèle dans PyTorch est encapsulé dans un tenseur. Ils ont la même fonction que les tableaux NumPy, mais sont optimisés pour le traitement sur des matériels spécialisés comme les GPU, ce qui les rend bien plus efficaces pour les opérations d'algèbre linéaire à grande échelle requises par les réseaux neuronaux.

Les propriétés clés définissent le tenseur :

  • Forme: Définit les dimensions des données, exprimées sous forme de tuple (par exemple, $4 \times 32 \times 32$ pour un lot d'images).
  • Type: Spécifie le type numérique des éléments stockés (par exemple, torch.float32 pour les poids du modèle, torch.int64 pour l'indexation).
  • Appareil: Indique l'emplacement matériel physique : généralement 'cpu' ou 'cuda' (GPU NVIDIA).
Graphe dynamique et Autograd
PyTorch utilise un modèle d'exécution impératif, ce qui signifie que le graphe computationnel est construit au fur et à mesure que les opérations sont exécutées. Cela permet au moteur intégré de différenciation automatique, Autograd, de suivre chaque opération sur un tenseur, à condition que la propriété requires_grad=True soit activée, permettant un calcul facile des gradients pendant la rétropropagation.
fundamentals.py
TERMINALbash — pytorch-env
> Ready. Click "Run" to execute.
>
TENSOR INSPECTOR Live

Run code to inspect active tensors
Question 1
Which command creates a $5 \times 5$ tensor containing random numbers following a uniform distribution between 0 and 1?
torch.rand(5, 5)
torch.random(5, 5)
torch.uniform(5, 5)
torch.randn(5, 5)
Question 2
If tensor $A$ is on the CPU, and tensor $B$ is on the CUDA device, what happens if you try to compute $A + B$?
An error occurs because operations require tensors on the same device.
PyTorch automatically moves $A$ to the CUDA device and proceeds.
The operation is performed on the CPU, and the result is returned to the CPU.
Question 3
What is the most common data type (dtype) used for model weights and intermediate calculations in Deep Learning?
torch.float32 (single-precision floating point)
torch.int64 (long integer)
torch.bool
torch.float64 (double-precision floating point)
Challenge: Tensor Manipulation and Shape
Prepare a tensor for a specific matrix operation.
You have a feature vector $F$ of shape $(10,)$. You need to multiply it by a weight matrix $W$ of shape $(10, 5)$. For matrix multiplication (MatMul) to work, $F$ must be 2-dimensional.
Step 1
What should the shape of $F$ be before multiplication with $W$?
Solution:
The inner dimensions must match, so $F$ must be $(1, 10)$. Then $(1, 10) @ (10, 5) \rightarrow (1, 5)$.
Code: F_new = F.unsqueeze(0) or F_new = F.view(1, -1)
Step 2
Perform the matrix multiplication between $F_{new}$ and $W$ (shape $(10, 5)$).
Solution:
The operation is straightforward MatMul.
Code: output = F_new @ W or output = torch.matmul(F_new, W)
Step 3
Which method explicitly returns a tensor with the specified dimensions, allowing you to flatten the tensor back to $(50,)$? (Assume $F$ was $(5, 10)$ initially and is now flattened.)
Solution:
Use the view or reshape methods. The fastest way to flatten is often using -1 for one dimension.
Code: F_flat = F.view(-1) or F_flat = F.reshape(50)